#include "options.h"
#include <string.h>
#include <stdlib.h>
using std::string; 

#ifndef __UNDERC__
void output_debug_str(const char *buff);
#else
#define output_debug_str printf
#endif

OptionsBase::OptionsBase(IniFile* inf, char* s)
: m_ini(inf),m_section(s)
{}

OptionsBase::~OptionsBase()
{ }


void OptionsBase::read()
{
 m_ini->set_section(m_section);
 m_writing = false;
 stream(false);
}

void OptionsBase::write()
{
 m_ini->set_section(m_section);
 m_writing = true;
 stream(true);
}

void OptionsBase::load_defaults()
{
// The Captain Haddock swearing here is to pretty much guarantee
// that our attempt to stream in will fail - so it will pick up
// the defaults!
 m_ini->set_section("???,,++%$???");
 m_writing = false;
 stream(false);
}

const int MAX_STRING = 256, MAX_NUM = 26;

void OptionsBase::map(pchar name, string& s, pchar def)
{
  char tmpbuff[MAX_STRING];
  if (m_writing)
    m_ini->write_string(name,s.c_str());
  else 
    s = m_ini->read_string(name,tmpbuff,sizeof(tmpbuff),def);
}

void OptionsBase::map(pchar name, int& val, int def)
{
  if (m_writing)
    m_ini->write_int(name,val);
  else
    val = m_ini->read_int(name,def);
}

char* f2a(double x)
{ 
    static char buff[MAX_NUM];
    return _gcvt(x,6,buff);
}

void OptionsBase::map(pchar name, float& val, float def)
{
   if (m_writing)
     m_ini->write_string(name,f2a(val));
   else
    val = atof(m_ini->read_string(name,f2a(def)));
}

// a specialized Options object used to save form position

FormOptions::FormOptions(TWin* p, IniFile* inf)
     : OptionsBase(inf,0)
{
 set_form(p);
}

FormOptions::~FormOptions()
{
  clear_form();
}

void FormOptions::set_form(TWin* p)
{
 m_form = p;
 if (m_form)  {
// the idea here is to find the first section of the form <name>#<num>
// which is not active.
   char buff[256];
   char* fname = m_form->get_text();
   int knt = 1;
   do {
     sprintf(buff,"%s#%d",fname,knt++);
     m_section = buff;
   } while (m_ini->read_int("open",0) != 0);
   m_section = strdup(buff);
 }
}

void FormOptions::clear_form()
{
    m_ini->write_int("open",0);
}

void FormOptions::stream(bool is_writing)
{
  if (is_writing) {
    Rect rt;   
    m_form->get_rect(rt,false);
    m_ini->write_int("x0",rt.left);
    m_ini->write_int("y0",rt.top);
    m_ini->write_int("wd",rt.right - rt.left);
    m_ini->write_int("ht",rt.bottom - rt.top);
    m_ini->write_int("open",1);
  } else {
    int x0 = m_ini->read_int("x0",-1);
    int y0 = m_ini->read_int("y0",-1);
    int wd = m_ini->read_int("wd",-1);
    int ht = m_ini->read_int("ht",-1);
    if (x0 != -1 && y0 != -1) {
       m_form->resize(x0,y0,wd,ht);       
    }
  }
}
